package org.jvending.provisioning.webservice.impl;

import org.jvending.provisioning.webservice.ServiceDeliverable;
import org.jvending.provisioning.webservice.DiscoveryService;
import org.jvending.provisioning.webservice.DiscoveryRequest;
import org.jvending.provisioning.webservice.ServiceException;
import org.codehaus.xfire.transport.http.XFireServletController;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;

import javax.servlet.ServletContext;
import javax.provisioning.ProvisioningContext;
import javax.provisioning.BundleDescriptor;
import java.util.List;
import java.util.Collection;
import java.util.ArrayList;
import java.io.IOException;

public class DiscoveryServiceImpl implements DiscoveryService, Initializable {

    private ProvisioningContext provisioningContext;

    public Collection<ServiceDeliverable> getServiceDeliverable(DiscoveryRequest discoveryRequest)
            throws ServiceException {
        if (discoveryRequest == null) {
            throw new IllegalArgumentException("discoveryRequest");
        }

        Collection<BundleDescriptor> bundleDescriptors;
        try {
            bundleDescriptors =
                    provisioningContext.getBundleRepository().getBundlesFor(null, null);
        } catch (IOException e) {
            throw new ServiceException("Problem locating bundles", e);
        }

        List<ServiceDeliverable> serviceDeliverables = new ArrayList<ServiceDeliverable>();
        for (BundleDescriptor bundleDescriptor : bundleDescriptors) {
            ServiceDeliverable serviceDeliverable = new ServiceDeliverableImpl();
            serviceDeliverable.setBundleId(bundleDescriptor.getBundleID());
            serviceDeliverable.setDeliveryUri(bundleDescriptor.getContentFile().getURL().toString());
            serviceDeliverable.setDescription(bundleDescriptor.getDescription(null));
            serviceDeliverables.add(serviceDeliverable);
        }

        return serviceDeliverables;
    }

    public void initialize() throws InitializationException {
        ServletContext servletContext =
                XFireServletController.getRequest().getSession().getServletContext().getContext("provisioning-portal");
        if (servletContext == null) {
            throw new InitializationException("Could not find provisioning portal context");
        }

        provisioningContext = (ProvisioningContext)
                servletContext.getAttribute("javax.provisioning.ProvisioningContext");
        if(provisioningContext == null)
        {
            throw new InitializationException("Could not find provisioning context.");
        }
    }

    protected void setProvisioningContext(ProvisioningContext provisioningContext)
    {
        this.provisioningContext = provisioningContext;
    }
}
